from typing import List, Optional, Dict, Any
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from sqlalchemy.orm import selectinload

from app.models.models import Course, Class
from app.schemas.schemas import CourseCreate


async def get_class_courses(
    db: AsyncSession, 
    class_code: str, 
    week: Optional[int] = None,
    day: Optional[int] = None
) -> Dict[str, Any]:
    """获取班级课程表"""
    # 获取班级信息
    class_result = await db.execute(
        select(Class).filter(Class.class_code == class_code)
    )
    class_obj = class_result.scalars().first()
    
    if not class_obj:
        return None
    
    # 构建课程查询
    query = select(Course).filter(Course.class_code == class_code)
    
    # 添加筛选条件
    if day:
        query = query.filter(Course.day_of_week == day)
    
    # 执行查询
    result = await db.execute(query)
    courses = result.scalars().all()
    
    # 如果指定了周次，过滤课程
    if week:
        filtered_courses = []
        for course in courses:
            weeks = course.weeks
            if isinstance(weeks, list) and week in weeks:
                filtered_courses.append(course)
        courses = filtered_courses
    
    # 构建响应数据
    class_info = {
        "class_code": class_obj.class_code,
        "class_name": class_obj.class_name,
        "college_name": class_obj.college_name
    }
    
    course_list = []
    for course in courses:
        course_data = {
            "course_name": course.course_name,
            "teacher": course.teacher,
            "day_of_week": course.day_of_week,
            "location": course.location,
            "section": course.section,
            "weeks": course.weeks,
            "courseType": course.courseType
        }
        course_list.append(course_data)
    
    return {
        "class_info": class_info,
        "courses": course_list
    }


async def create_course(db: AsyncSession, course: CourseCreate) -> Course:
    """创建课程"""
    db_course = Course(**course.model_dump())
    db.add(db_course)
    await db.commit()
    await db.refresh(db_course)
    return db_course
